package com.wtwd.campus.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wtwd.campus.annotation.AuditLog;
import com.wtwd.campus.common.Constants;
import com.wtwd.campus.common.RespCode;
import com.wtwd.campus.common.RespCodeEntity;
import com.wtwd.campus.common.RespEntity;
import com.wtwd.campus.entity.*;
import com.wtwd.campus.service.DeviceClassPatternService;
import com.wtwd.campus.service.DeviceInfoService;
import com.wtwd.campus.service.DeviceSettingService;
import com.wtwd.campus.service.RedisService;
import com.wtwd.campus.utils.*;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/device")
public class DeviceController {
    private static final Logger logger = LoggerFactory.getLogger(DeviceController.class);

    @Autowired
    private RedisService redisService;
    @Autowired
    private DeviceInfoService deviceInfoService;
    @Autowired
    public GetCurrentSysUserInfoUtils getCurrentSysUserInfoUtils;
    @Autowired
    public CommandSendUtils commandSendUtils;
    @Autowired
    public DeviceClassPatternService deviceClassPatternService;
    @Autowired
    public DeviceSettingService deviceSettingService;
    @Autowired
    private ReceiverUtils receiverUtils;

    /**
     * 获取SIM卡列表
     *
     * @param request
     * @return
     */
    @PostMapping("/getSimCardList")
    public RespEntity getSimCardList(@RequestBody QuerySimCardDataVo data, HttpServletRequest request) {
        logger.info("getSimCardList: data = {}", data.toString());
        //获取用户的组织编号
        String userOrgCode = getUserOrgCode(request);
        if (StringUtils.isBlank(data.getOrgCode())) {
            data.setOrgCode(userOrgCode);
        }
        //查询SIM卡列表信息
        Map<String, Object> result = deviceInfoService.getSimCardList(data);
        return new RespEntity(RespCode.SUCCESS, result);
    }

    /**
     * 修改sim卡号
     *
     * @param data
     * @return
     */
    @PutMapping("/modifySimCard")
    public RespEntity modifySimCard(@RequestBody ModifyDeviceDataVo data) {
        logger.info("modifySimCard: data = {}", data.toString());
        return deviceInfoService.modifySimCard(data);
    }


    /**
     * 获取用户组织编码
     *
     * @param request
     * @return
     */
    public String getUserOrgCode(HttpServletRequest request) {
        String token = request.getHeader(Constants.HEADER_TOKEN_KEY);
        Map<String, Object> msg = redisService.getUserInfoByToken(token);
        String userMsg = (String) msg.get("user");
        JSONObject jsonObject = JSONObject.parseObject(userMsg);
        String userOrgCode = (String) jsonObject.get("orgCode");
        return userOrgCode;
    }

    /**
     * 获取用户信息
     *
     * @param request
     * @return
     */
    public JSONObject getUserInfo(HttpServletRequest request) {
        String token = request.getHeader(Constants.HEADER_TOKEN_KEY);
        Map<String, Object> msg = redisService.getUserInfoByToken(token);
        String userMsg = (String) msg.get("user");
        JSONObject jsonObject = JSONObject.parseObject(userMsg);
        return jsonObject;
    }


    /**
     * 条件获取设备列表
     *
     * @param jsonObject
     * @return
     */
    @PostMapping("/getDeviceInfo")
    public RespEntity getDeviceInfo(@RequestBody JSONObject jsonObject) {
        logger.info("getDeviceInfo: param = {}", jsonObject);
        Integer currentPage = jsonObject.getInteger("currentPage");
        Integer pageSize = jsonObject.getInteger("pageSize");
        String imei = jsonObject.getString("imei");
        String stuName = jsonObject.getString("stuName");
        String stuPhone = jsonObject.getString("stuPhone");
        String model = jsonObject.getString("model");
        //状态1:在线,2离线
        Integer start = jsonObject.getInteger("start");
        //工作模式1定位模式  2省电模式
        Integer workingPattern = jsonObject.getInteger("workingPattern");
        //同步(false:不同步,true同步)
        String flag = jsonObject.getString("synchronization");
        Integer synchronization = 1;
        if (flag.equals("false")) {
            synchronization = 0;
        } else {
            synchronization = 1;
        }
        String orgCode = jsonObject.getString("orgCode");
        SysUser sysUser = getCurrentSysUserInfoUtils.getCurrentSysUserInfo();
        if (sysUser == null) {
            return new RespEntity(RespCode.TOKEN_UNAUTHORIZED);
        }
        if (StringUtils.isBlank(orgCode)) {//如果orgCode为空默认查当前用户的设备
            orgCode = sysUser.getOrgCode();
        }
        long time = new Date().getTime() - Constants.OFF_LINE_TIME;
        Page<Object> page = new Page<>(currentPage, pageSize);
        //构建查询map
        HashMap<String, Object> searchMap = new HashMap<>();
        searchMap.put("imei", imei);
        searchMap.put("synchronization", synchronization);
        searchMap.put("stuName", stuName);
        searchMap.put("stuPhone", stuPhone);
        searchMap.put("model", model);
        searchMap.put("time", time);
        searchMap.put("start", start);
        searchMap.put("workingPattern", workingPattern);
        searchMap.put("orgCode", orgCode);
        Map<String, Object> restMap = deviceInfoService.getDeviceInfoListByCondition(searchMap, page);
        return new RespEntity(RespCode.SUCCESS, restMap);
    }

    /**
     * 添加校园卡
     *
     * @param deviceInfo
     * @return
     */
    @PostMapping("/addDeviceInfo")
    @AuditLog(operationType = "添加校园卡", operationContent = "", orgCode = "")
    public RespCodeEntity addDeviceInfo(@RequestBody DeviceInfo deviceInfo) {
        logger.info("addDeviceInfo: param = {}", deviceInfo);
        RespCodeEntity respCodeEntity = deviceInfoService.checkDeviceInfo(deviceInfo);
        if (respCodeEntity.getCode() != RespCode.SUCCESS.getCode()) {
            return respCodeEntity;
        }
        Integer rest = deviceInfoService.saveDeviceInfo(deviceInfo);
        //添加操作日志
        if (rest > 0) {
            Method method = null;
            try {
                method = DeviceController.class.getMethod("addDeviceInfo", DeviceInfo.class);
                //获取操作的组织的code
                String orgCode = deviceInfo.getOrgCode();
                String operationContent = "添加".concat(deviceInfo.getImei()).concat("校园卡");
                AuditLogUtils.modifyAnnotation(method, operationContent, orgCode);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
        }
/*        //初步添加设备完成，从设备端获取参数
        //添加操作日志
        if (rest > 0) {
            Method method = null;
            try {
                method = DeviceController.class.getMethod("addDeviceInfo", DeviceInfo.class);
                //获取操作的组织的code
                String orgCode = deviceInfo.getOrgCode();
                String operationContent = "添加".concat(deviceInfo.getImei()).concat("校园卡");
                AuditLogUtils.modifyAnnotation(method, operationContent, orgCode);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
        }
        //初步添加设备完成，从设备端获取参数
        String commandNumber = getCurTime();
        boolean online = commandSendUtils.deviceOnline(deviceInfo.getImei());
        SysUser sysUser = getCurrentSysUserInfoUtils.getCurrentSysUserInfo();
        if (sysUser == null) {
            return new RespCodeEntity(RespCode.TOKEN_UNAUTHORIZED);
        }
        commandSendUtils.getDeviceParam(deviceInfo.getImei(), commandNumber, sysUser.getUserId(), online, false);*/
        return new RespCodeEntity(rest > 0 ? RespCode.SUCCESS : RespCode.FAILED);
    }

    /**
     * 删除校园卡
     *
     * @param deviceId
     * @return
     */

    @DeleteMapping("/deleteDevice/{deviceId}")
    @AuditLog(operationType = "删除校园卡", operationContent = "", orgCode = "")
    public RespCodeEntity deleteDevice(@PathVariable("deviceId") Integer deviceId) {
        logger.info("deleteDevice: param = {}", deviceId);
        SysUser sysUser = getCurrentSysUserInfoUtils.getCurrentSysUserInfo();
        if (sysUser == null) {
            return new RespCodeEntity(RespCode.TOKEN_UNAUTHORIZED);
        }
        //根据设备id获取设备信息
        DeviceInfo device = deviceInfoService.getDeviceInfoByDeviceId(deviceId);
        if (device.getStudentId() != null) {
            return new RespCodeEntity(RespCode.DEVICE_BIND_STUDENT);
        }
        //恢复设备出厂设置
        boolean online = commandSendUtils.deviceOnline(device.getImei());
        String commandNumber = CommandNumberUtil.getCurTime();
        commandSendUtils.reSetDevice(device.getImei(), commandNumber, online, sysUser.getUserId(), false);
        //删除设备数据
        Integer i = deviceInfoService.deleteDeviceById(deviceId);
        //添加操作日志
        if (device != null && i > 0) {
            Method method = null;
            try {
                method = DeviceController.class.getMethod("deleteDevice", Integer.class);
                //获取操作的组织的code
                String orgCode = device.getOrgCode();
                String operationContent = "删除".concat(device.getImei()).concat("校园卡");
                AuditLogUtils.modifyAnnotation(method, operationContent, orgCode);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
        }
        return new RespCodeEntity(i > 0 ? RespCode.SUCCESS : RespCode.FAILED);
    }

    /**
     * 导出校园卡
     *
     * @param jsonObject
     * @param response
     * @return
     */

    @PostMapping("/exportDeviceInfo")
    @AuditLog(operationType = "批量导出设备", operationContent = "", orgCode = "")
    public RespEntity exportDeviceInfo(@RequestBody JSONObject jsonObject, HttpServletResponse response) {
        logger.info("getDeviceInfo: param = {}", jsonObject);
        String imei = jsonObject.getString("imei");
        String stuName = jsonObject.getString("stuName");
        String stuPhone = jsonObject.getString("stuPhone");
        String model = jsonObject.getString("model");
        //状态1:在线,2离线
        Integer start = jsonObject.getInteger("start");
        //工作模式1定位模式  2省电模式 3无GPS模式 4无定位模式 5短信模式
        Integer workingPattern = jsonObject.getInteger("workingPattern");
        //同步(0:不同步,1同步)
        Integer synchronization = jsonObject.getInteger("synchronization");
        String orgCode = jsonObject.getString("orgCode");
        SysUser sysUser = getCurrentSysUserInfoUtils.getCurrentSysUserInfo();
        if (sysUser == null) {
            return new RespEntity(RespCode.TOKEN_UNAUTHORIZED);
        }
        if (StringUtils.isBlank(orgCode)) {//如果orgCode为空默认查当前用户的设备
            orgCode = sysUser.getOrgCode();
        }
        long time = new Date().getTime() - Constants.OFF_LINE_TIME;
        //构建查询map
        HashMap<String, Object> searchMap = new HashMap<>();
        searchMap.put("imei", imei);
        searchMap.put("synchronization", synchronization);
        searchMap.put("stuName", stuName);
        searchMap.put("stuPhone", stuPhone);
        searchMap.put("model", model);
        searchMap.put("time", time);
        searchMap.put("start", start);
        searchMap.put("workingPattern", workingPattern);
        searchMap.put("orgCode", orgCode);
        List<ExcelExportDeviceInfo> excelExportDeviceInfos = deviceInfoService.ExcelExportDeviceInfo(searchMap);
        Integer successNum = 0;
        if (excelExportDeviceInfos != null) {
            successNum = excelExportDeviceInfos.size();
        }
        String path = MyExcelUtils.exportExcel(excelExportDeviceInfos, "设备信息", "设备信息", ExcelExportDeviceInfo.class, "设备信息.xls", response);
        //添加操作日志
        if (!StringUtils.isBlank(path)) {
            Method method = null;
            try {
                method = DeviceController.class.getMethod("exportDeviceInfo", JSONObject.class, HttpServletResponse.class);
                //获取操作的组织的code
                String operationContent = "导出".concat(String.valueOf(successNum)).concat("条校园卡信息");
                AuditLogUtils.modifyAnnotation(method, operationContent, orgCode);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
        }
        return new RespEntity(RespCode.SUCCESS, path);
    }

    /**
     * 导入设备
     *
     * @param file
     * @param orgCode
     * @param orgName
     * @param response
     * @return
     */
    @PostMapping("/importDeviceInfo")
    @AuditLog(operationType = "批量导入设备", operationContent = "", orgCode = "")
    public RespEntity importDeviceInfo(@RequestParam("file") MultipartFile file, @RequestParam("orgCode") String orgCode, @RequestParam("orgName") String orgName, HttpServletResponse response) {
        logger.info("importDeviceInfo: param = {}", orgCode, orgName);
        RespEntity respEntity = deviceInfoService.importDeviceInfo(file, orgCode, orgName, response);
        //添加操作日志
        if (respEntity.getCode() == RespCode.SUCCESS.getCode()) {
            Method method = null;
            try {
                method = DeviceController.class.getMethod("importDeviceInfo", MultipartFile.class, String.class, String.class, HttpServletResponse.class);
                //获取操作的组织的code
                Map<String, Object> map = (Map<String, Object>) respEntity.getData();
                Integer successNum = (Integer) map.get("successNum");
                String operationContent = "导入".concat(String.valueOf(successNum)).concat("条校园卡信息");
                AuditLogUtils.modifyAnnotation(method, operationContent, orgCode);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
        }
        return respEntity;
    }

    /**
     * 接入客户，导入设备
     *
     * @param file
     * @param response
     * @return
     */
    @PostMapping("/importCustomerDeviceInfo")
    public RespEntity importCustomerDeviceInfo(@RequestBody MultipartFile file, HttpServletResponse response) {
        logger.info("importCustomerDeviceInfo: param = {}", file);
        return deviceInfoService.importCustomerDeviceInfo(file, response);
    }


    /**
     * 根据设备id获取课堂模式
     *
     * @param deviceId
     * @return
     */
    @GetMapping("/getClassesPattern/{deviceId}")
    public RespEntity getClassesPattern(@PathVariable("deviceId") Integer deviceId) {
        logger.info("getClassesPattern: param = {}", deviceId);
        List<DeviceClassPattern> deviceClassPatterns = deviceClassPatternService.getDeviceClassesPatternByDeviceId(deviceId);
        return new RespEntity(RespCode.SUCCESS, deviceClassPatterns);
    }


    /**
     * 添加课堂模式
     *
     * @param jsonObject
     * @return
     */
    @PostMapping("/addClassesPattern")
    public RespEntity addClassesPattern(@RequestBody JSONObject jsonObject) {
        logger.info("addClassesPattern: param = {}", jsonObject);
        SysUser sysUser = getCurrentSysUserInfoUtils.getCurrentSysUserInfo();
        if (sysUser == null) {
            return new RespEntity(RespCode.TOKEN_UNAUTHORIZED);
        }
        String imei = jsonObject.getString("imei");
        Integer deviceId = jsonObject.getInteger("deviceId");
        String jsonString = jsonObject.getString("classPatterns");
        List<DeviceClassMode> deviceClassPatterns = new ArrayList<>();
        if (StringUtils.isNotBlank(jsonString)) {
            deviceClassPatterns = JSONArray.parseArray(jsonString, DeviceClassMode.class);
        }
        return deviceClassPatternService.addClassesPattern(imei, deviceId, deviceClassPatterns, sysUser);
    }

    /**
     * 删除课堂模式
     *
     * @param id
     * @return
     */
    @DeleteMapping("/deleteClassesPattern/{id}")
    public RespEntity deleteClassesPattern(@PathVariable("id") Integer id) {
        logger.info("deleteClassesPattern: param = {}", id);
        SysUser sysUser = getCurrentSysUserInfoUtils.getCurrentSysUserInfo();
        if (sysUser == null) {
            return new RespEntity(RespCode.TOKEN_UNAUTHORIZED);
        }
        return deviceClassPatternService.deleteClassesPattern(id, sysUser);
    }

    /**
     * 设置默认监控中心
     *
     * @param jsonObject
     * @return
     */
    @PostMapping("/setDefaultControlCenter")
    public RespEntity setDefaultControlCenter(@RequestBody JSONObject jsonObject) {
        logger.info("setDefaultControlCenter,jsonObject={}" + jsonObject);
        SysUser sysUser = getCurrentSysUserInfoUtils.getCurrentSysUserInfo();
        if (sysUser == null) {
            return new RespEntity(RespCode.TOKEN_UNAUTHORIZED);
        }
        String imei = jsonObject.getString("imei");
        String commandNumber = getCurTime();
        String ipAddress = jsonObject.getString("ipAddress");
        Integer port = jsonObject.getInteger("port");
        boolean online = commandSendUtils.deviceOnline(imei);
        boolean b = commandSendUtils.setDefaultServerIpAndPort(imei, commandNumber, ipAddress, port, online, sysUser.getUserId(), false);
        return new RespEntity(b ? RespCode.SUCCESS : RespCode.FAILED);
    }

    /**
     * 设置终端操作 type:1(关机) type：2(重启) type 3：恢复出厂设置
     *
     * @param jsonObject
     * @return
     */
    @PostMapping("/settingTerminal")
    public RespEntity settingTerminal(@RequestBody JSONObject jsonObject) {
        logger.info("settingTerminal,jsonObject={}" + jsonObject);
        SysUser sysUser = getCurrentSysUserInfoUtils.getCurrentSysUserInfo();
        if (sysUser == null) {
            return new RespEntity(RespCode.TOKEN_UNAUTHORIZED);
        }
        Integer type = jsonObject.getInteger("type");
        String imei = jsonObject.getString("imei");
        boolean online = commandSendUtils.deviceOnline(imei);
        //如果操作是重启,或者关机,只有在线才会发送
        if (!type.equals(3)) {
            if (!online) {//终端操作指令，只有在线才能发送
                return new RespEntity(RespCode.DEVICE_NOT_ONLINE);
            }
        }
        String commandNumber = getCurTime();
        boolean result = false;
        switch (type) {
            case 1:
                result = commandSendUtils.shutDownDevice(imei, commandNumber, sysUser.getUserId());
                break;
            case 2:
                result = commandSendUtils.restartDevice(imei, commandNumber, sysUser.getUserId());
                break;
            case 3:
                result = commandSendUtils.reSetDevice(imei, commandNumber, online, sysUser.getUserId(), false);
                break;
        }
        return new RespEntity(result ? RespCode.SUCCESS : RespCode.FAILED);
    }


    /**
     * 音量调节
     *
     * @param jsonObject
     * @return
     */
    @PostMapping("/volume")
    public RespEntity volume(@RequestBody JSONObject jsonObject) {
        logger.info("settingVolume,jsonObject={}" + jsonObject);
        SysUser sysUser = getCurrentSysUserInfoUtils.getCurrentSysUserInfo();
        if (sysUser == null) {
            return new RespEntity(RespCode.TOKEN_UNAUTHORIZED);
        }
        String imei = jsonObject.getString("imei");
        String commandNumber = CommandNumberUtil.getCurTime();
        Integer speakLevel = jsonObject.getInteger("speakLevel");//0：小,1：中,2：大
        boolean online = commandSendUtils.deviceOnline(imei);
        boolean rest = commandSendUtils.adjustVolume(imei, commandNumber, speakLevel, online, sysUser.getUserId(), false);
        return new RespEntity(rest ? RespCode.SUCCESS : RespCode.FAILED);
    }

    /**
     * 设置定位模式
     *
     * @param jsonObject
     * @return
     */
    @PostMapping("/setLocationModel")
    public RespEntity setLocationModel(@RequestBody JSONObject jsonObject) {
        logger.info("setLocationModel,jsonObject={}" + jsonObject);
        SysUser sysUser = getCurrentSysUserInfoUtils.getCurrentSysUserInfo();
        if (sysUser == null) {
            return new RespEntity(RespCode.TOKEN_UNAUTHORIZED);
        }
        Integer type = jsonObject.getInteger("type");
        String imei = jsonObject.getString("imei");
        Integer interval = jsonObject.getInteger("interval");
        boolean online = commandSendUtils.deviceOnline(imei);
        String commandNumber = getCurTime();
        boolean result = false;
        if (type.equals(Constants.DEFAULT_WORK_PATTERN)) {//实时定位模式
            if (interval == null) {
                interval = Constants.UP_INTERVAL;
            }
            result = commandSendUtils.setDeviceMode(imei, commandNumber, Constants.DEFAULT_WORK_PATTERN, interval, online, sysUser.getUserId(), false);
        } else if (type.equals(Constants.POWER_SAVING_MODEL)) {//省电模式
            if (interval == null) {
                interval = Constants.POWER_SAVING_MODEL_UP_INTERVAL;
            }
            result = commandSendUtils.setDeviceMode(imei, commandNumber, Constants.POWER_SAVING_MODEL, interval, online, sysUser.getUserId(), false);
        }
        return new RespEntity(result ? RespCode.SUCCESS : RespCode.FAILED);
    }


    /**
     * 设置监听模式
     *
     * @param jsonObject
     * @return
     */
    @PostMapping("/setMonitorPhone")
    public RespEntity setMonitorPhone(@RequestBody JSONObject jsonObject) {
        logger.info("setMonitorPhone,jsonObject={}" + jsonObject);
        SysUser sysUser = getCurrentSysUserInfoUtils.getCurrentSysUserInfo();
        if (sysUser == null) {
            return new RespEntity(RespCode.TOKEN_UNAUTHORIZED);
        }
        String imei = jsonObject.getString("imei");
        String phone = jsonObject.getString("phone");
        String commandNumber = getCurTime();
        DeviceInfo deviceInfo = deviceInfoService.getDeviceByImei(imei);
        Boolean authMonitorNumber =deviceInfoService.authMonitorNumber(deviceInfo.getDeviceId(),phone);
        if (!authMonitorNumber){
            return new RespEntity(RespCode.MONITOR_PHONE_ERROR);
        }
        boolean online = commandSendUtils.deviceOnline(imei);
        if (!online) {//设备不在线不发
            return new RespEntity(RespCode.DEVICE_NOT_ONLINE);
        }
        boolean result = commandSendUtils.setMonitorPhone(imei, commandNumber, phone, sysUser.getUserId());
        return new RespEntity(result ? RespCode.SUCCESS : RespCode.FAILED);
    }

    /**
     * 设置睡眠模式
     *
     * @param jsonObject
     * @param request
     * @return
     */
    @PostMapping("/setSleepMode")
    public RespEntity setSleepMode(@RequestBody JSONObject jsonObject,
                                   HttpServletRequest request) {
        logger.info("setSleepMode: param", jsonObject);
        String imei = jsonObject.getString("imei");
        String start = jsonObject.getString("start");
        String end = jsonObject.getString("end");
        Integer flag = jsonObject.getInteger("flag");
        boolean isOnline = deviceOnline(imei);
        String commandNumber = getCurTime();
        Integer userId = getUserId(request);
        boolean b = commandSendUtils.setSleepTimeAutoChangeMode(imei, commandNumber, start, end, flag, true, userId, false);
        if (isOnline) {
            if (b) {
                //如果设备在线且指令发送成功，则修改数据库设备睡眠模式信息
                DeviceSetting deviceSetting = deviceSettingService.getDeviceSettingByImei(imei);
                deviceSetting.setSleepSwitch(flag);
                deviceSetting.setSleepStart(start);
                deviceSetting.setSleepEnd(end);
                deviceSettingService.modifyDeviceSetting(deviceSetting);
            }
        }
        return new RespEntity(b ? RespCode.SUCCESS : RespCode.FAILED);
    }

    /**
     * 主动查询设备定位信息
     */
    @GetMapping("/getDeviceLocationMess/{imei}")
    public RespEntity getDeviceLocationMess(@PathVariable("imei") String imei,
                                            HttpServletRequest request) {
        logger.info("setSleepMode:imei= {}", imei);
        boolean isOnline = true;
        String commandNumber = getCurTime();
        Integer userId = getUserId(request);
        boolean b = commandSendUtils.queryDeviceLocation(imei, commandNumber, userId, true, false);
        return new RespEntity(b ? RespCode.SUCCESS : RespCode.FAILED);
    }

    /**
     * 获取设备参数
     */
    @GetMapping("/getDeviceParam/{imei}")
    public RespEntity getDeviceParam(@PathVariable("imei") String imei,
                                     HttpServletRequest request) {
        logger.info("setSleepMode:imei= {}", imei);
        boolean isOnline = deviceOnline(imei);
        String commandNumber = getCurTime();
        Integer userId = getUserId(request);
        boolean b = commandSendUtils.getDeviceParam(imei, commandNumber, userId, isOnline, false);
        return new RespEntity(b ? RespCode.SUCCESS : RespCode.FAILED);
    }

    /**
     * 查询sim卡号和iccid
     */
    @GetMapping("/getSimAndIccId/{imei}")
    public RespEntity getSimAndIccId(@PathVariable("imei") String imei,
                                     HttpServletRequest request) {
        logger.info("getSimAndIccId:imei= {}", imei);
        boolean isOnline = deviceOnline(imei);
        String commandNumber = getCurTime();
        Integer userId = getUserId(request);
        boolean b = commandSendUtils.getDeviceIccidAndSimCardNo(imei, commandNumber, userId, isOnline, false);
        return new RespEntity(b ? RespCode.SUCCESS : RespCode.FAILED);
    }

    /**
     * 获取机身imeid
     */
    @GetMapping("/getDeviceImeid/{imei}")
    public RespEntity getDeviceImeid(@PathVariable("imei") String imei,
                                     HttpServletRequest request) {
        logger.info("getDeviceImeid:imei= {}", imei);
        boolean isOnline = deviceOnline(imei);
        String commandNumber = getCurTime();
        Integer userId = getUserId(request);
        boolean b = commandSendUtils.getDeviceImeid(imei, commandNumber, userId, isOnline, false);
        return new RespEntity(b ? RespCode.SUCCESS : RespCode.FAILED);
    }

    /**
     * 设置临时监控中心
     */
    @GetMapping("/setTemController/{imei}")
    public RespEntity setTemController(@PathVariable("imei") String imei,
                                       HttpServletRequest request) {
        logger.info("setTemController:imei= {}", imei);
        boolean isOnline = deviceOnline(imei);
        String commandNumber = getCurTime();
        Integer userId = getUserId(request);
        boolean b = commandSendUtils.setTempServerIpAndPort(imei, commandNumber, "112.74.176.68", 9090, userId, isOnline, false);
        return new RespEntity(b ? RespCode.SUCCESS : RespCode.FAILED);
    }

    /**
     * 设置工作模式
     */
    @GetMapping("/getDeviceWorkMode/{imei}")
    public RespEntity getDeviceWorkMode(@PathVariable("imei") String imei,
                                        HttpServletRequest request) {
        logger.info("getDeviceImeid:imei= {}", imei);
        boolean isOnline = deviceOnline(imei);
        String commandNumber = getCurTime();
        Integer userId = getUserId(request);
        boolean b = commandSendUtils.setDeviceMode(imei, commandNumber, 1, 150, isOnline, userId, false);
        return new RespEntity(b ? RespCode.SUCCESS : RespCode.FAILED);
    }

    /**
     * 判断设备是否在线
     *
     * @param imei 设备imei号
     * @return 设备是否在线
     */
    public boolean deviceOnline(String imei) {
        boolean isOnline = redisService.hasKey(Constants.DEVICE_ONLINE_PREFIX + imei);
        logger.info("设备:【{}】: {}", imei, isOnline ? "在线" : "离线");
        return isOnline;
    }

    /**
     * 闲时自动切换工作模式
     *
     * @param imei 设备imei号
     * @return 设备是否在线
     */
    @GetMapping("/autoChangeWorkMode/{imei}")
    public RespEntity autoChangeWorkMode(@PathVariable("imei") String imei,
                                         HttpServletRequest request) {
        logger.info("autoChangeWorkMode:imei= {}", imei);
        boolean isOnline = deviceOnline(imei);
        String commandNumber = getCurTime();
        /*Integer userId = getUserId(request);*/
        Integer userId = 1;
        boolean b = commandSendUtils.setSleepTimeAutoChangeMode(imei, commandNumber, "17:50", "18:20", 1, true, userId, false);
        return new RespEntity(b ? RespCode.SUCCESS : RespCode.FAILED);
    }

    /**
     * 设置监听
     *
     * @param imei 设备imei号
     * @return 设备是否在线
     */
    @GetMapping("/setMonitor/{imei}")
    public RespEntity setMonitor(@PathVariable("imei") String imei,
                                 HttpServletRequest request) {
        logger.info("setMonitor:imei= {}", imei);
        String commandNumber = getCurTime();
        Integer userId = getUserId(request);
        boolean b = commandSendUtils.setMonitorPhone(imei, commandNumber, "15270797517", userId);
        return new RespEntity(b ? RespCode.SUCCESS : RespCode.FAILED);
    }

    /**
     * 音量调节
     *
     * @param imei 设备imei号
     * @return 设备是否在线
     */
    @GetMapping("/setSpeakLevel/{imei}")
    public RespEntity setSpeakLevel(@PathVariable("imei") String imei,
                                    HttpServletRequest request) {
        logger.info("setSpeakLevel:imei= {}", imei);
        String commandNumber = getCurTime();
        Integer userId = getUserId(request);
        boolean b = commandSendUtils.adjustVolume(imei, commandNumber, 2, true, userId, false);
        return new RespEntity(b ? RespCode.SUCCESS : RespCode.FAILED);
    }

    /**
     * 软件关机
     *
     * @param imei 设备imei号
     * @return 设备是否在线
     */
    @GetMapping("/turnOff/{imei}")
    public RespEntity turnOff(@PathVariable("imei") String imei,
                              HttpServletRequest request) {
        logger.info("turnOff:imei= {}", imei);
        String commandNumber = getCurTime();
        Integer userId = getUserId(request);
        boolean b = commandSendUtils.shutDownDevice(imei, commandNumber, userId);
        return new RespEntity(b ? RespCode.SUCCESS : RespCode.FAILED);
    }

    /**
     * 设备上报间隔的设置
     *
     * @param imei 设备imei号
     * @return 设备是否在线
     */
    @GetMapping("/setUploadInterval/{imei}")
    public RespEntity setUploadInterval(@PathVariable("imei") String imei,
                                        HttpServletRequest request) {
        logger.info("setUploadInterval:imei= {}", imei);
        String commandNumber = getCurTime();
        Integer userId = getUserId(request);
        boolean b = commandSendUtils.setUploadInterval(imei, commandNumber, 280, true, userId, false);
        return new RespEntity(b ? RespCode.SUCCESS : RespCode.FAILED);
    }


    /**
     * 设置PDOP门限值
     *
     * @param imei 设备imei号
     * @return 设备是否在线
     */
    @GetMapping("/setPDOP/{imei}")
    public RespEntity setPDOP(@PathVariable("imei") String imei,
                              HttpServletRequest request) {
        logger.info("setPDOP:imei= {}", imei);
        String commandNumber = getCurTime();
        Integer userId = getUserId(request);
        boolean b = commandSendUtils.setPDOP(imei, commandNumber, 4, true, userId, false);
        return new RespEntity(b ? RespCode.SUCCESS : RespCode.FAILED);
    }

    /**
     * SOS拨号开关的设置
     *
     * @param imei 设备imei号
     * @return 设备是否在线
     */
    @GetMapping("/setSOSSwitch/{imei}")
    public RespEntity setSOSSwitch(@PathVariable("imei") String imei,
                                   HttpServletRequest request) {
        logger.info("setSOSSwitch:imei= {}", imei);
        String commandNumber = getCurTime();
        Integer userId = getUserId(request);
        boolean b = commandSendUtils.setSOSSwitch(imei, commandNumber, 1, true, userId, false);
        return new RespEntity(b ? RespCode.SUCCESS : RespCode.FAILED);
    }

    /**
     * 重启
     *
     * @param imei 设备imei号
     * @return 设备是否在线
     */
    @GetMapping("/reStart/{imei}")
    public RespEntity reStart(@PathVariable("imei") String imei,
                              HttpServletRequest request) {
        logger.info("reStart:imei= {}", imei);
        String commandNumber = getCurTime();
        Integer userId = getUserId(request);
        boolean b = commandSendUtils.restartDevice(imei, commandNumber, userId);
        return new RespEntity(b ? RespCode.SUCCESS : RespCode.FAILED);
    }

    /**
     * 设备id切换
     *
     * @param imei 设备imei号
     * @return 设备是否在线
     */
    @GetMapping("/chooseDeviceId/{imei}")
    public RespEntity chooseDeviceId(@PathVariable("imei") String imei,
                                     HttpServletRequest request) {
        logger.info("chooseDeviceId:imei= {}", imei);
        String commandNumber = getCurTime();
        Integer userId = getUserId(request);
        boolean b = commandSendUtils.exchangeDeviceId(imei, commandNumber, 0, userId, true, false);
        return new RespEntity(b ? RespCode.SUCCESS : RespCode.FAILED);
    }

    /**
     * 主动获取步数信息
     *
     * @param imei 设备imei号
     * @return 设备是否在线
     */
    @GetMapping("/getStep/{imei}")
    public RespEntity getStep(@PathVariable("imei") String imei,
                              HttpServletRequest request) {
        logger.info("getStep:imei= {}", imei);
        String commandNumber = getCurTime();
        Integer userId = getUserId(request);
        boolean b = commandSendUtils.getDeviceStep(imei, commandNumber, userId, true, false);
        return new RespEntity(b ? RespCode.SUCCESS : RespCode.FAILED);
    }

    /**
     * m1卡号的变更
     *
     * @param imei 设备imei号
     * @return 设备是否在线
     */
    @GetMapping("/setM1/{imei}")
    public RespEntity setM1(@PathVariable("imei") String imei,
                            HttpServletRequest request) {
        logger.info("setM1:imei= {}", imei);
        String commandNumber = getCurTime();
        Integer userId = getUserId(request);
        boolean b = commandSendUtils.updateM1Card(imei, commandNumber, "ALOE01002707", userId, true, false);
        return new RespEntity(b ? RespCode.SUCCESS : RespCode.FAILED);
    }

    /**
     * 清楚绑定信息
     *
     * @param imei 设备imei号
     * @return 设备是否在线
     */
    @GetMapping("/cleanBanding/{imei}")
    public RespEntity cleanBanding(@PathVariable("imei") String imei,
                                   HttpServletRequest request) {
        logger.info("cleanBanding:imei= {}", imei);
        String commandNumber = getCurTime();
        Integer userId = getUserId(request);
        boolean b = commandSendUtils.cleanBandingMess(imei, commandNumber, userId, true, false);
        return new RespEntity(b ? RespCode.SUCCESS : RespCode.FAILED);
    }

    /**
     * 设置临时端口
     *
     * @param imei 设备imei号
     * @return 设备是否在线
     */
    @GetMapping("/setTemPort/{imei}")
    public RespEntity setTemPort(@PathVariable("imei") String imei,
                                 HttpServletRequest request) {
        logger.info("setTemPort:imei= {}", imei);
        String commandNumber = getCurTime();
        Integer userId = getUserId(request);
        boolean b = commandSendUtils.setTempServerIpAndPort(imei, commandNumber, "112.74.176.68", 9090, userId, true, false);
        return new RespEntity(b ? RespCode.SUCCESS : RespCode.FAILED);
    }

    /**
     * 一次性设置白名单
     *
     * @param imei 设备imei号
     * @return 设备是否在线
     */
    @GetMapping("/setAllWhite/{imei}")
    public RespEntity setAllWhite(@PathVariable("imei") String imei,
                                  HttpServletRequest request) {
        logger.info("setAllWhite:imei= {}", imei);
        String commandNumber = getCurTime();
        Integer userId = getUserId(request);
        List<Map<String, Object>> list = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        map.put("name", "梅");
        map.put("phone", "13669061320");
        map.put("sequence", "1");
/*        Map<String, Object> map3 = new HashMap<>();
        map3.put("name", "梅");
        map3.put("phone", "15180419204");
        map3.put("sequence", "2");
        Map<String, Object> map4 = new HashMap<>();
        map4.put("name", "梅花");
        map4.put("phone", "13669061320");
        map4.put("sequence", "3");*/
        list.add(map);
        /*list.add(map3);*/
        /*list.add(map4);*/
        for (int i = 2; i < 6; i++) {
            Map<String, Object> map2 = new HashMap<>();
            String name = "测".concat(String.valueOf(i));
            String phone = "1376776122".concat(String.valueOf(i));
            map2.put("name", name);
            map2.put("phone", phone);
            map2.put("sequence", String.valueOf(i));
            list.add(map2);
        }
        Map<String, Object> map7 = new HashMap<>();
        map7.put("name", "信");
        map7.put("phone", "15180419204");
        map7.put("sequence", "7");
        list.add(map7);
        boolean b = commandSendUtils.setAllWhiteCall(list, imei, commandNumber, true, userId, false);
        return new RespEntity(b ? RespCode.SUCCESS : RespCode.FAILED);
    }

    /**
     * 单个设置白名单
     *
     * @param imei 设备imei号
     * @return 设备是否在线
     */
    @GetMapping("/setSingleWhite/{imei}")
    public RespEntity setSingleWhite(@PathVariable("imei") String imei,
                                     HttpServletRequest request) {
        logger.info("setSingleWhite:imei= {}", imei);
        String commandNumber = getCurTime();
        Integer userId = getUserId(request);
        List<Map<String, Object>> list = new ArrayList<>();
      /*  Map<String ,Object> map=new HashMap<>();
        map.put("name","aaa");
        map.put("phone","15180419204");
        map.put("sequence","1");
        list.add(map);*/
        DeviceWhiteCall deviceWhiteCall = new DeviceWhiteCall();
        deviceWhiteCall.setName("蓝2");
        deviceWhiteCall.setPhone("15180419204");
        deviceWhiteCall.setSequence(1);
        deviceWhiteCall.setCommandNumber(commandNumber);
        deviceWhiteCall.setImei(imei);
        boolean b = commandSendUtils.updateDeviceWhiteCall(deviceWhiteCall, true, userId, false);
        return new RespEntity(b ? RespCode.SUCCESS : RespCode.FAILED);
    }

    /**
     * 回复出厂设置
     *
     * @param imei 设备imei号
     * @return 设备是否在线
     */
    @GetMapping("/factoryReset/{imei}")
    public RespEntity factoryReset(@PathVariable("imei") String imei,
                                   HttpServletRequest request) {
        logger.info("factoryReset:imei= {}", imei);
        String commandNumber = getCurTime();
        Integer userId = getUserId(request);
        boolean b = commandSendUtils.reSetDevice(imei, commandNumber, true, userId, false);
        return new RespEntity(b ? RespCode.SUCCESS : RespCode.FAILED);
    }

    /**
     * 课堂模式的开关
     *
     * @param imei 设备imei号
     * @return 设备是否在线
     */
    @GetMapping("/setClassModeSwitch/{imei}")
    public RespEntity setClassModeSwitch(@PathVariable("imei") String imei,
                                         HttpServletRequest request) {
        logger.info("setClassModeSwitch:imei= {}", imei);
        String commandNumber = getCurTime();
        Integer userId = getUserId(request);
        boolean b = commandSendUtils.updateClassModeAllSwitch(imei, commandNumber, 1, true, userId, false);
        return new RespEntity(b ? RespCode.SUCCESS : RespCode.FAILED);
    }


    /**
     * 白名单的开关
     *
     * @param imei 设备imei号
     * @return 设备是否在线
     */
    @GetMapping("/setWhiteSwitch/{imei}")
    public RespEntity setWhiteSwitch(@PathVariable("imei") String imei,
                                     HttpServletRequest request) {
        logger.info("setWhiteSwitch:imei= {}", imei);
        String commandNumber = getCurTime();
        Integer userId = getUserId(request);
        boolean b = commandSendUtils.setWhiteCallSwitch(imei, commandNumber, 0, userId, true, false);
        return new RespEntity(b ? RespCode.SUCCESS : RespCode.FAILED);
    }

    /**
     * 获取当前时间的时分秒（HHmmss）
     *
     * @return
     */
    public String getCurTime() {
        Date d = new Date();
        SimpleDateFormat sbf = new SimpleDateFormat("HH:mm:ss");
        String format = sbf.format(d);
        String[] split = format.split(":");
        String time = split[0].concat(split[1]).concat(split[2]);
        return time;
    }

    /**
     * 获取用户id
     *
     * @param request
     * @return
     */
    public Integer getUserId(HttpServletRequest request) {
        //获取用户的组织编号
        String token = request.getHeader(Constants.HEADER_TOKEN_KEY);
        Map<String, Object> msg = redisService.getUserInfoByToken(token);
        String userMsg = (String) msg.get("user");
        JSONObject jsonObject = JSONObject.parseObject(userMsg);
        Integer userId = (Integer) jsonObject.get("userId");
        return userId;
    }


    /**
     * 设置免打扰时间开关设置免打扰时间开关
     *
     * @param jsonObject
     * @return
     */
    @PostMapping("/setClassWitch")
    public RespEntity setClassWitch(@RequestBody JSONObject jsonObject) {
        SysUser sysUser = getCurrentSysUserInfoUtils.getCurrentSysUserInfo();
        if (sysUser == null) {
            new RespEntity(RespCode.TOKEN_UNAUTHORIZED);
        }
        String imei = jsonObject.getString("imei");
        Integer flag = jsonObject.getInteger("flag");
        String commandNumber = CommandNumberUtil.getCurTime();
        boolean online = commandSendUtils.deviceOnline(imei);
        boolean rest = commandSendUtils.updateClassModeAllSwitch(imei, commandNumber, flag, online, sysUser.getUserId(), false);
        return new RespEntity(rest ? RespCode.SUCCESS : RespCode.FAILED);
    }

    /**
     * 获取设备设置信息
     */
    @GetMapping("/getDeviceInfoSetting/{deviceId}")
    public RespEntity getDeviceInfoSetting(@PathVariable("deviceId") Integer deviceId) {
        logger.info("setWhiteSwitch:deviceId= {}", deviceId);
        DeviceSetting deviceSetting = deviceSettingService.getDeviceSettingByDeviceId(deviceId);
     /*   //根据设备id获取工作模式和上传时间间隔
        DeviceInfo deviceInfo = deviceInfoService.getDeviceInfoByDeviceId(deviceId);
        String s = JSONObject.toJSONString(deviceSetting);
        JSONObject jsonObject = JSONObject.parseObject(s);
        jsonObject.put("workPattern", deviceInfo.getWorkingPattern() == null ? Constants.DEFAULT_WORK_PATTERN : deviceInfo.getWorkingPattern());
        jsonObject.put("upInterval", deviceInfo.getUpInterval() == null ? Constants.UP_INTERVAL : deviceInfo.getUpInterval());*/
        return new RespEntity(RespCode.SUCCESS, deviceSetting);
    }

    /**
     * 条件查询第三方设备信息列表
     *
     * @param data
     * @param request
     * @return
     */
    @PostMapping("/queryThirdPartDeviceList")
    public RespEntity queryThirdPartDeviceList(@RequestBody ThirdPartDeviceVO data, HttpServletRequest request) {
        logger.info("/queryThirdPartDeviceList:data = {}", data.toString());
        Map<String, Object> result = deviceInfoService.getThirdPartDeviceList(data);
        return new RespEntity(RespCode.SUCCESS, result);
    }

    /**
     * 删除第三方设备
     *
     * @param deviceId
     * @return
     */
    @DeleteMapping("/deleteThirdPartDeviceList/{deviceId}")
    @AuditLog(operationType = "删除第三方设备", operationContent = "", orgCode = "")
    public RespEntity deleteThirdPartDeviceList(@PathVariable("deviceId") Integer deviceId) {
        logger.info("deleteThirdPartDeviceList: param = {}", deviceId);
        SysUser sysUser = getCurrentSysUserInfoUtils.getCurrentSysUserInfo();
        if (sysUser == null) {
            return new RespEntity(RespCode.TOKEN_UNAUTHORIZED);
        }
        //根据设备id获取设备信息
        DeviceInfo device = deviceInfoService.getDeviceInfoByDeviceId(deviceId);
        if (device == null) {
            return new RespEntity(RespCode.DEVICE_NOT_EXIST);
        }
        //删除设备数据
        Integer i = deviceInfoService.deleteDeviceById(deviceId);
        if (i > 0) {
            //恢复设备出厂设置
            boolean online = commandSendUtils.deviceOnline(device.getImei());
            String commandNumber = CommandNumberUtil.getCurTime();
            boolean b = commandSendUtils.reSetDevice(device.getImei(), commandNumber, online, sysUser.getUserId(), false);
            if (b) {
                //添加操作日志
                if (i > 0) {
                    Method method = null;
                    try {
                        method = DeviceController.class.getMethod("deleteThirdPartDeviceList", Integer.class);
                        //获取操作的组织的code
                        String orgCode = "A01";
                        String operationContent = "删除".concat(device.getImei()).concat("校园卡");
                        AuditLogUtils.modifyAnnotation(method, operationContent, orgCode);
                    } catch (NoSuchMethodException e) {
                        e.printStackTrace();
                    }
                }
                return new RespEntity(RespCode.SUCCESS);
            }
            return new RespEntity(RespCode.FAILED);
        }
        return new RespEntity(RespCode.FAILED);
    }

    /**
     * 导入第三方设备
     *
     * @param file
     * @param response
     * @return
     */
    @PostMapping("/importThirdPartDevice")
    @AuditLog(operationType = "批量导入第三方设备", operationContent = "", orgCode = "")
    public RespEntity importThirdPartDevice(@RequestParam("file") MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
        JSONObject userInfo = getUserInfo(request);
        if (userInfo == null) {
            return new RespEntity(RespCode.USER_INDEX_EXPIRE);
        }
        Integer userId = userInfo.getInteger("userId");
        logger.info("/importThirdPartDevice: userId = {}", userId.toString());
        RespEntity respEntity = deviceInfoService.importThirdPartDevice(file, response);
        //添加操作日志
        if (respEntity.getCode() == RespCode.SUCCESS.getCode()) {
            Method method = null;
            try {
                method = DeviceController.class.getMethod("importThirdPartDevice", MultipartFile.class, HttpServletRequest.class, HttpServletResponse.class);
                //获取操作的组织的code
                Map<String, Object> map = (Map<String, Object>) respEntity.getData();
                Integer successNum = (Integer) map.get("successNum");
                String operationContent = "成功导入".concat(String.valueOf(successNum)).concat("条校园卡信息");
                AuditLogUtils.modifyAnnotation(method, operationContent, "A01");
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
        }
        return respEntity;
    }

    /**
     * 导入设备
     *
     * @param file
     * @param response
     * @return
     */
    @PostMapping("/importH5NXDevice")
    public RespEntity importH5NXDevice(@RequestParam("file") MultipartFile file, @RequestParam("mode") String mode, HttpServletRequest request, HttpServletResponse response) {
        RespEntity respEntity = deviceInfoService.importNXDevice(file, response, mode);
        return respEntity;
    }

    /**
     * 导入威科姆设备
     */

    @PostMapping("/importVcomDevice")
    public RespEntity importVcomDevice(@RequestParam("file") MultipartFile file, HttpServletResponse response) {
        return deviceInfoService.importVcomDevice(file, response);
    }

    /**
     * 联通认证后的设备导入
     *
     * @param file
     * @param response
     * @return
     */
    @PostMapping("/importVcomLtDevice")
    public RespEntity importVcomLtDevice(@RequestParam("file") MultipartFile file, HttpServletResponse response) {
        return deviceInfoService.importVcomLtDevice(file, response);
    }

    /**
     * 根据imei查询设备
     *
     * @param imei
     * @return
     */
    @GetMapping("/queryDeviceInfoByImei/{imei}")
    public DeviceInfo queryDeviceInfoByImei(@PathVariable("imei") String imei) {
        return deviceInfoService.getDeviceByImei(imei);
    }


}
